<template>
    <div class="login"
         v-loading="loading"
         element-loading-spinner="el-icon-loading"
         element-loading-text="正在登录中"
         element-loading-background="rgba(0, 0, 0, 0.8)">
        <!--头部-->
        <div class="login-header">

            <div class="logo">
                <h1>
                    <router-link :to="{name:'home'}" title="解忧杂货店"></router-link>
                </h1>

                <div class="login-msg error" style="text-align: center;width: 880px; margin: 0 auto;">
                    <p class="error" style="float: none;width: auto;">
                        为确保您账户的安全及正常使用，依《网络安全法》相关要求，6月1日起会员账户需绑定手机。如您还未绑定，请尽快完成，感谢您的理解及支持！
                    </p>
                </div>

                <a href="javascript:;" class="link" @click="$store.dispatch('invalidBtnAlertAction')">
                    <i class="el-icon-s-comment"></i>&nbsp;"登录页面"改进建议
                </a>
            </div>

        </div>
        <!--身体-->
        <div class="login-content">
            <!--大背景-->
            <div class="login-newbg"
                 style="background-image: url(https://gtms04.alicdn.com/tps/i4/TB1Q6JIjNz1gK0jSZSgSuuvwpXa.jpg);height:600px;">
            </div>
            <!--大背景A跳转-->
            <div class="login-adlink">
                <router-link :to="{name:'home'}" title="解忧杂货店"></router-link>
            </div>
            <!--登录表单-->
            <div class="content-layout">
                <div class="login-box-warp">

                    <div class="login-box no-longlogin module-static">
                        <!--登录方式切换按钮-->
                        <div id="switch-loginway"
                             style="height: 52px;position: absolute;top:10px;right:10px;z-index: 999;cursor: pointer;">

                            <img v-show="loginWay.code !== 1" src="../../assets/tip-pwd.png" alt=""
                                 style="width: 75px;height: 45px;user-select: none;cursor:default">
                            <img v-show="loginWay.code === 1" src="../../assets/tip-qrcode.png" alt=""
                                 style="width: 125px;height: 45px;user-select: none;cursor:default; ">
                            <img v-show="loginWay.code !== 1"
                                 @click="handleSwitchLoginWay(1)"
                                 src="../../assets/account-btn.png" alt="密码登录" style="width: 52px;height: 52px;">
                            <img v-show="loginWay.code === 1"
                                 @click="handleSwitchLoginWay(3)"
                                 src="../../assets/qrcode-btn.png" alt="二维码登录" style="width: 52px;height: 52px;">
                        </div>

                        <!--login box begin-->
                        <div class="bd">
                            <!--标准登录框-->
                            <div class="static-form " id="J_StaticForm" v-show="loginWay.code === 1">
                                <div class="login-title">

                                    密码登录

                                </div>
                                <el-form :model="loginForm" :rules="loginRules" ref="loginForm" label-width="0"
                                         class="J_Form" method="post"
                                >
                                    <div id="J_Message" style="display:none;" class="login-msg error">
                                        <i class="iconfont"></i>

                                        <p class="error"></p>

                                    </div>
                                    <!-- 手机号登录 -->
                                    <div class="field username-field">
                                        <el-form-item prop="username">
                                            <el-input v-model="loginForm.username" placeholder="会员名/邮箱/手机号"
                                                      id="TPL_username"
                                                      name="TPL_username"
                                                      class="login-text"
                                                      clearable
                                                      autofocus
                                                      tabindex="1" prefix-icon="el-icon-s-custom"></el-input>
                                        </el-form-item>
                                    </div>
                                    <!--密码框-->
                                    <div class="field pwd-field">
                                        <el-form-item prop="password">
                                            <el-input placeholder="请输入您的密码" v-model="loginForm.password"
                                                      prefix-icon="el-icon-lock"
                                                      style="user-select: none;"
                                                      id="TPL_password" name="TPL_password"
                                                      class="login-text" show-password></el-input>
                                        </el-form-item>
                                    </div>

                                    <!--滑动验证-->
                                    <drag-verify :width="dragParam.width"
                                                 :height="dragParam.height"
                                                 :text="dragParam.text"
                                                 :success-text="dragParam.successText"
                                                 :background="dragParam.background"
                                                 :progress-bar-bg="dragParam.progressBarBg"
                                                 :completed-bg="dragParam.completedBg"
                                                 :handler-bg="dragParam.handlerBg"
                                                 :handler-icon="dragParam.handlerIcon"
                                                 :text-size="dragParam.textSize"
                                                 :success-icon="dragParam.successIcon"
                                                 :circle="dragParam.circle"
                                                 ref="Verify"
                                                 style='margin-top: 20px;font: 10px/3.4 "Microsoft YaHei", tahoma, arial, "Hiragino Sans GB", "\5b8b\4f53", sans-serif !important'>
                                    </drag-verify>

                                    <div class="submit">

                                        <!-- 子账号跳转方式 -->
                                        <el-button :loading="loading" :plain="true"
                                                   @click.native.prevent="handleLogin('loginForm')" class="J_Submit"
                                                   id="J_SubmitStatic">登
                                            录
                                        </el-button>
                                    </div>

                                    <ul class="entries">
                                        <li id="J_OtherLogin" class="other-login">

                                            <a href="javascript:;" @click="handleSwitchLoginWay(2)"
                                               class="face-login">
                                                <i class="el-icon-user"/>
                                                <span>人脸登录</span>
                                                <img src="//gtms01.alicdn.com/tps/i1/TB12zErIFXXXXa3XpXXkSlfFpXX-20-13.gif"
                                                     alt="new" style="position: absolute; top: 2px; right: 7px;">
                                            </a>

                                            <a href="javascript:;" @click="handleSwitchLoginWay(4)"
                                               tabindex="4" class="weibo-login">
                                                <i class="el-icon-mobile-phone"/>
                                                <span>短信快捷登录</span>
                                            </a>

                                            <!-- <a href="javascript:;" @click="$store.dispatch('invalidBtnAlertAction')"
                                                tabindex="5" class="alipay-login">
                                                 <i class="zfb-icon"/>
                                                 <span>支付宝登录</span>
                                             </a>-->


                                        </li>
                                    </ul>


                                    <div class="login-links">


                                        <a href="javascript:;" @click="$store.dispatch('invalidBtnAlertAction')"
                                           tabindex="6" class="forget-pwd" target="_blank">
                                            忘记密码</a>

                                        <a href="javascript:;" @click="$store.dispatch('invalidBtnAlertAction')"
                                           target="_blank">忘记会员名</a>

                                        <router-link :to="{name:'register'}" class="register">免费注册</router-link>

                                    </div>

                                </el-form>
                            </div>

                            <!--人脸登录框-->
                            <div class="face-form" v-show="loginWay.code === 2">
                                <div class="login-title">

                                    人脸登录

                                </div>
                                <div style="width: 300px;position: relative;margin-top: 60px;">
                                    <video id="videoCamera" :width="videoWidth" :height="videoHeight" autoplay></video>
                                    <canvas style="display:none;" id="canvasCamera" :width="videoWidth"
                                            :height="videoHeight"></canvas>
                                    <img src="../../assets/face-mask.gif" alt=""
                                         style="width: 300px;height: 200px;opacity: .2;position: absolute;left: 0;top:0;">
                                </div>

                                <p id="faceLoginTipP" :style="faceLoginTipObj.style">
                                    {{faceLoginTipObj.message}}
                                </p>
                            </div>

                            <!--二维码登录框-->
                            <div class="qrcode-form" v-show="loginWay.code === 3">
                                <div class="login-title">

                                    手机扫码，安全登录

                                </div>

                                <div style="width:100%;text-align: center;">
                                    <a @click="refreshQrCodeA" href="javascript:;"
                                       style="color: rgb(255,68,0)">刷新二维码</a>
                                </div>


                                <div style="width: 300px;height: 200px;position: relative;">
                                    <div style="width: 300px;height: 200px;text-align:center;position: absolute;left: 0;top:0;">
                                        <img :src="qrcodeObj.content"
                                             alt=""
                                             v-loading="qrcodeObj.loading"
                                             style="width: 200px;height: 200px;"
                                             :style="qrcodeObj.filter?'-webkit-filter: blur(8px);filter: blur(8px)':''">
                                        <i v-show="qrcodeObj.filter" class="el-icon-check" :style="qrcodeObj.style"
                                           style="
                                            position: absolute;
                                            left: 50%;
                                            top: 50%;
                                            transform: translateX(-50%) translateY(-50%);
                                            font-size: 60px;color: green;font-weight: 900;"></i>
                                    </div>

                                </div>

                                <div class="qrcodeLoginTipP" style="width: 100%;">
                                    请使用
                                    <el-popover
                                            placement="right"
                                            trigger="manual"
                                            v-model="visible">
                                        <img src="../../assets/miniprogram.png"
                                             alt="" class="pic_code_qrcode" style="width: 200px;height: 200px;">
                                        <a href="javascript:;" style="color: #2468f2;" @mouseenter="visible = true"
                                           @mouseout="visible = false"
                                           slot="reference">解忧App</a>
                                    </el-popover>
                                    扫码登录
                                </div>

                                <p class="qrcodeLoginTipP" :style="qrcodeObj.style" style="width: 100%;">
                                    {{qrcodeObj.message}}
                                </p>

                            </div>

                            <!--短信快捷登录框-->
                            <div class="static-form" id="J_PhoneForm" v-show="loginWay.code === 4">
                                <div class="login-title">

                                    短信登录

                                </div>
                                <el-form :model="phoneForm" :rules="phoneRules" ref="phoneForm" label-width="0"
                                         class="J_Form" method="post">
                                    <!-- 手机号登录 -->
                                    <div class="field">
                                        <el-form-item prop="phone">
                                            <el-input placeholder="手机号"
                                                      v-model="phoneForm.phone"
                                                      name="phone"
                                                      class="login-text"
                                                      clearable
                                                      autofocus
                                                      prefix-icon="el-icon-mobile-phone"></el-input>
                                        </el-form-item>
                                    </div>
                                    <!--验证码-->
                                    <div class="field" style="width: 120px;">
                                        <el-form-item prop="code">
                                            <el-input placeholder="请输入验证码"
                                                      prefix-icon="el-icon-lock"
                                                      name="code"
                                                      v-model="phoneForm.code"
                                                      class="login-text"></el-input>
                                        </el-form-item>
                                        <el-button
                                                :disabled="phoneForm.sending"
                                                icon="el-icon-message"
                                                class="send-code-btn" @click="sendPhoneCode">
                                            {{phoneForm.text}}
                                        </el-button>
                                    </div>

                                    <!--滑动验证-->
                                    <drag-verify :width="dragParam.width"
                                                 :height="dragParam.height"
                                                 :text="dragParam.text"
                                                 :success-text="dragParam.successText"
                                                 :background="dragParam.background"
                                                 :progress-bar-bg="dragParam.progressBarBg"
                                                 :completed-bg="dragParam.completedBg"
                                                 :handler-bg="dragParam.handlerBg"
                                                 :handler-icon="dragParam.handlerIcon"
                                                 :text-size="dragParam.textSize"
                                                 :success-icon="dragParam.successIcon"
                                                 :circle="dragParam.circle"
                                                 ref="Verify2"
                                                 style='margin-top: 20px;font: 10px/3.4 "Microsoft YaHei", tahoma, arial, "Hiragino Sans GB", "\5b8b\4f53", sans-serif !important'>
                                    </drag-verify>

                                    <div class="submit">

                                        <!-- 子账号跳转方式 -->
                                        <el-button :loading="loading" :plain="true"
                                                   @click.native.prevent="handlePhoneLogin('phoneForm')"
                                                   class="J_Submit">登
                                            录
                                        </el-button>
                                    </div>

                                    <ul class="entries">
                                        <li class="other-login">

                                            <a href="javascript:;" @click="handleSwitchLoginWay(2)"
                                               class="face-login">
                                                <i class="el-icon-user"/>
                                                <span>人脸登录</span>
                                                <img src="//gtms01.alicdn.com/tps/i1/TB12zErIFXXXXa3XpXXkSlfFpXX-20-13.gif"
                                                     alt="new" style="position: absolute; top: 2px; right: 7px;">
                                            </a>

                                            <a href="javascript:;" @click="handleSwitchLoginWay(1)"
                                               tabindex="4" class="weibo-login">
                                                <i class="el-icon-monitor"/>
                                                <span>密码登录</span>
                                            </a>

                                            <!-- <a href="javascript:;" @click="$store.dispatch('invalidBtnAlertAction')"
                                                tabindex="5" class="alipay-login">
                                                 <i class="zfb-icon"/>
                                                 <span>支付宝登录</span>
                                             </a>-->


                                        </li>
                                    </ul>


                                    <div class="login-links">


                                        <a href="javascript:;" @click="$store.dispatch('invalidBtnAlertAction')"
                                           tabindex="6" class="forget-pwd" target="_blank">
                                            忘记密码</a>

                                        <a href="javascript:;" @click="$store.dispatch('invalidBtnAlertAction')"
                                           target="_blank">忘记会员名</a>

                                        <router-link :to="{name:'register'}" class="register">免费注册</router-link>

                                    </div>

                                </el-form>
                            </div>

                        </div>
                    </div>
                </div>
                <!--标准登录框结束-->
            </div>
        </div>
        <!--尾部-->
        <Footer/>
    </div>
</template>

<script>
    import Footer from "@/components/Footer";
    import dragVerify from 'vue-drag-verify'
    import {checkFace} from "../../api/facelogin";
    import {validateLoginPhoneNum, sendLoginPhoneCode, getQrCode, checkQrCode} from "../../api/user"


    export default {
        name: "Login",
        components: {Footer, dragVerify},
        data() {
            /*手机号校验*/
            const validatePhoneNumRule = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入您的手机号'));
                } else if (!/^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/.test(value)) {
                    callback(new Error('手机号格式不对！'));
                } else {
                    /*发送请求*/
                    validateLoginPhoneNum(this.phoneForm.phone)
                        .then((data) => {
                            if (data.code === 20000 || data.success) {
                                callback();  // 一定要有，这是表单校验成功后的回调，会返回一个boolean值，即true
                            } else {
                                callback(new Error(data.message))
                            }
                        })
                }
            }
            /*手机验证码校验*/
            const validatePhoneCodeRule = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入手机验证码'));
                } else if (!/^[0-9]{4}$/.test(value)) {
                    callback(new Error('手机验证码格式不对'));
                } else {
                    callback();
                }

            }
            return {
                /*JieYou-wechat微信小程序二维码 是否显示*/
                visible: false,
                /*二维码扫描情况提示*/
                qrcodeObj: {
                    loadding: false, //二维码加载
                    filter: true, //滤镜,用于扫码成功后的蒙版效果
                    message: "",  //提示信息
                    style: {}, //提示样式
                    code: "", //二维码唯一标识
                    content: "", //二维码文件
                    checkTimer: "",   //定时器,用于轮询查询二维码状态
                    isScan: false //是否已经扫描,用于自动更新二维码
                },
                /*加载动画*/
                loading: false,
                /* 登录表单 */
                loginForm: {
                    username: 'xsf',
                    password: '123456',
                },
                /*短信快捷登录表单*/
                phoneForm: {
                    phone: '13763055759',
                    code: '',
                    sending: false,// 发送中
                    text: "免费获取验证码",// 文字提示
                    timer: '', //定时器
                    isSuccess: '', //是否发送成功
                    fallback: '',// 错误反馈
                },
                /* 表单规则 */
                loginRules: {
                    username: [
                        {required: true, message: '请输入帐号', trigger: 'blur'},
                        {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'change'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'change'}
                    ],
                },
                /* 短信快捷登录规则 */
                phoneRules: {
                    phone: [
                        {validator: validatePhoneNumRule, trigger: 'blur'}
                    ],
                    code: [
                        {validator: validatePhoneCodeRule, trigger: 'blur'}
                    ],
                },

                /*滑动验证框*/
                dragParam: {
                    /*
                            名称 | 类型 | 默认值 | 说明
                            --- | --- | --- | ---
                            width | Number | 200 | 组件的宽度
                            height | Number | 60 | 组件的高度
                            text | String | swiping to the right side | 提示信息文字
                            successText | String | success | 验证通过时的提示信息文字
                            background | String | #ccc | 组件背景色
                            color | String | #ffffff | 组件文字颜色
                            progressBarBg | String | #FFFF99 | 拖拽过程中的背景颜色
                            completedBg | String | #66cc66 | 验证成功的背景颜色
                            circle | Boolean | true | 设为true,组件为圆形按钮，否则为长方形
                            handlerIcon | String | - | 拖拽按钮的icon
                            successIcon | String | - | 验证通过时拖拽按钮的icon
                            handlerBg | String | #fff | 拖拽按钮的背景色
                            textSize | String | 20px | 组件的文字大小
                    */
                    circle: false, /*圆角*/
                    text: '请按住滑块，拖动到最右边',
                    width: 300,
                    height: 40,
                    textSize: "12px",
                    successText: '验证通过',   /*成功提示*/
                    progressBarBg: "rgb(122,196,40)",/*进度条背景色*/
                    completedBg: 'rgb(122,196,60)',/*完成后背景色*/
                    handlerBg: "#fff",
                    handlerIcon: 'el-icon-d-arrow-right',
                    successIcon: 'el-icon-check'
                },

                /*登录方式,1:账号密码,2:人脸登录,3:扫码登录,4:手机验证码登录*/
                loginWays: [
                    {code: 1, title: "密码登录"},
                    {code: 2, title: "人脸登录"},
                    {code: 3, title: "扫码登录"},
                    {code: 4, title: "手机验证码登录"},
                ],
                loginWay: {code: 1, title: "密码登录"},
                /*人脸识别摄像头高宽*/
                videoWidth: 300,
                videoHeight: 200,
                /*人脸识别定时器*/
                timer: "",
                /*人脸登录提示信息*/
                faceLoginTipObj: {style: {}, message: "人脸验证中,请稍等..."},
                /*摄像头权限是否开启*/
                cameraPermissionIsOpen: false
            }
        },
        methods: {
            /*登录按钮事件*/
            handleLogin() {
                this.$refs['loginForm'].validate((valid) => {
                    if (valid) {
                        /*人机验证*/
                        if (!this.$refs.Verify.isPassing) {
                            this.$notify.error({
                                title: '提交失败',
                                message: '请滑动滑块完成人机验证'
                            })
                            return false;
                        }
                        /*开启加载动画*/
                        this.loading = true
                        /*发送请求*/
                        this.$store.dispatch('user/login', this.loginForm).then(() => {
                            this.$message.success('登录成功！');
                            this.$router.push({path: this.redirect || '/'})
                        }).finally(() => {
                            /*关闭加载动画*/
                            this.loading = false
                        })
                    } else {
                        return false;
                    }
                });
            },
            /*短信快捷登录按钮事件*/
            handlePhoneLogin() {
                this.$refs['phoneForm'].validate((valid) => {
                    if (valid) {
                        /*人机验证*/
                        if (!this.$refs.Verify2.isPassing) {
                            this.$notify.error({
                                title: '提交失败',
                                message: '请滑动滑块完成人机验证'
                            })
                            return false;
                        }
                        /*发送请求*/
                        this.$store.dispatch('user/phoneLogin', this.phoneForm).then(() => {
                            this.$router.push({path: this.redirect || '/'})
                        }).catch(e => {
                            this.$message.error(e);
                        })
                    } else {
                        return false;
                    }
                });
            },
            /*手机验证码发送按钮点击*/
            sendPhoneCode() {
                let second = 60
                this.phoneForm.sending = true
                clearInterval(this.phoneForm.timer)
                this.phoneForm.timer = setInterval(() => {
                    second--
                    this.phoneForm.text = `${second}s后重新发送`
                    if (second === 0) {
                        clearInterval(this.phoneForm.timer)
                        this.phoneForm.text = '免费获取验证码'
                        this.phoneForm.sending = false
                    }
                }, 1000)
                /*发送请求:发送验证码*/
                sendLoginPhoneCode(this.phoneForm.phone)
                    .then((data) => {
                        if (data.code === 20000 || data.success) {
                            this.phoneForm.isSuccess = true
                            this.phoneForm.fallback = ''
                        } else {
                            this.phoneForm.isSuccess = false
                            this.phoneForm.fallback = data.message
                        }
                    })
            },
            /*切换登录方式事件*/
            async handleSwitchLoginWay(num) {
                // 清除定时器
                clearInterval(this.timer);
                clearInterval(this.qrcodeObj.checkTimer);

                this.loginWay = this.loginWays[num - 1]
                // 人脸登录
                if (num === 2) {
                    this.faceLoginTipObj = {
                        style: {},
                        message: "正在请求授权打开摄像头..."
                    }
                    // 1.打开摄像头
                    await this.openCamera()
                    // 判断是否开启了摄像头权限
                    if (!this.cameraPermissionIsOpen) {//未开启
                        this.faceLoginTipObj = {
                            style: {"color": "red"},
                            message: "您已拒绝授权，人脸识别不可用"
                        }
                        return
                    }
                    this.faceLoginTipObj = {
                        style: {},
                        message: "授权成功，正在人脸识别"
                    }
                    // 2.开启定时器,拍照,3s上传一次判断有效性
                    this.timer = setInterval(this.faceLoginFun, 3000)
                }
                // 二维码登录
                else if (num === 3) {
                    this.getQrCodeFunc()
                }
            },
            /*人脸登录*/
            faceLoginFun() {
                // 获取base64格式照片
                let base64File = this.takePhoto()
                // base64 => file
                let file = this.dataURLtoFile(base64File, "filename.png")
                // 发送请求:图像检测
                let param = new FormData(); //创建form对象
                param.append('file', file);//通过append向form对象添加数据
                checkFace(param).then((data) => {
                    let {success, code, message} = data
                    console.log("checkFace:", data);
                    // 图片检测反馈
                    if (success) { // 成功:发送请求-人脸登录
                        this.faceLoginTipObj = {
                            style: {color: "blue"},
                            message: "人脸识别成功，等待用户身份识别"
                        }
                        // 1.停止定时器
                        clearInterval(this.timer)
                        // 2.发送请求:人脸登录
                        this.$store.dispatch('user/faceLogin', param)
                            .then((message) => {
                                this.closeCamera() //关闭摄像头
                                // 登录成功
                                this.faceLoginTipObj = {
                                    style: {color: "blue"},
                                    message: "用户识别成功，即将跳转"
                                }
                                this.$router.push({path: this.redirect || '/'})
                            })
                            .catch(message => { // 登录失败
                                this.faceLoginTipObj = {
                                    style: {"color": "red"},
                                    message: "识别失败，请重试或使用其他方式登录"
                                }
                                // 重新开启定时器
                                clearInterval(this.timer)
                                this.timer = setInterval(this.faceLoginFun, 3000)
                            })
                    } else { // 失败:反馈结果,继续检测
                        this.faceLoginTipObj = {
                            style: {color: "red"},
                            message: "未检测到人脸"
                        }
                    }
                }).catch((error) => {
                    console.log(error)
                })
            },
            // 调用权限（打开摄像头功能）
            async openCamera() {
                var _this = this
                this.thisCancas = document.getElementById('canvasCamera')
                this.thisContext = this.thisCancas.getContext('2d')
                this.thisVideo = document.getElementById('videoCamera')
                // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
                if (navigator.mediaDevices === undefined) {
                    navigator.mediaDevices = {}
                }
                // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
                // 使用getUserMedia，因为它会覆盖现有的属性。
                // 这里，如果缺少getUserMedia属性，就添加它。
                if (navigator.mediaDevices.getUserMedia === undefined) {
                    navigator.mediaDevices.getUserMedia = function (constraints) {
                        // 首先获取现存的getUserMedia(如果存在)
                        var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia
                        // 有些浏览器不支持，会返回错误信息
                        // 保持接口一致
                        if (!getUserMedia) {
                            return Promise.reject(new Error('getUserMedia is not implemented in this browser'))
                        }
                        // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
                        return new Promise(function (resolve, reject) {
                            getUserMedia.call(navigator, constraints, resolve, reject)
                        })
                    }
                }
                var constraints = {
                    audio: false,
                    video: {width: this.videoWidth, height: this.videoHeight, transform: 'scaleX(-1)'}
                }
                await navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
                    // 旧的浏览器可能没有srcObject
                    if ('srcObject' in _this.thisVideo) {
                        _this.thisVideo.srcObject = stream
                    } else {
                        // 避免在新的浏览器中使用它，因为它正在被弃用。
                        _this.thisVideo.src = window.URL.createObjectURL(stream)
                    }
                    _this.thisVideo.onloadedmetadata = function (e) {
                        _this.thisVideo.play()
                    }
                    _this.cameraPermissionIsOpen = true //允许了摄像头权限
                    console.log("允许了摄像头权限")
                }).catch(err => {
                    _this.cameraPermissionIsOpen = false //拒绝了摄像头权限
                    console.log("拒绝了摄像头权限:",err)
                })

            },
            //  绘制图片（拍照功能）
            takePhoto() {
                // 点击，canvas画图
                this.thisContext.drawImage(this.thisVideo, 0, 0, this.videoWidth, this.videoHeight)
                // 获取图片base64链接
                return this.thisCancas.toDataURL('image/png')
            },
            // base64转文件
            dataURLtoFile(dataurl, filename) {
                var arr = dataurl.split(',')
                var mime = arr[0].match(/:(.*?);/)[1]
                var bstr = atob(arr[1])
                var n = bstr.length
                var u8arr = new Uint8Array(n)
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n)
                }
                return new File([u8arr], filename, {type: mime})
            },
            // 关闭摄像头
            closeCamera() {
                this.thisVideo.srcObject.getTracks()[0].stop()
            },

            /*刷新二维码按钮*/
            refreshQrCodeA() {
                this.getQrCodeFunc()
            },
            /*封装获取获取二维码的方法*/
            getQrCodeFunc() {
                // 清除定时器
                clearInterval(this.qrcodeObj.checkTimer);
                this.qrcodeObj.filter = false //关闭滤镜
                this.qrcodeObj.isScan = false //未曾扫描,用于决定是否自动更新二维码
                this.qrcodeObj.message = ""

                // 1.获取二维码
                this.qrcodeObj.loading = true //开启特效
                getQrCode().then((res) => {
                    // 2.赋值
                    const {code, content} = res.data
                    this.qrcodeObj.code = code
                    this.qrcodeObj.content = content
                    // 3.开启检查二维码状态定时器
                    this.checkQrcodeTimerFunc()
                }).finally(() => {
                    this.qrcodeObj.loading = false //关闭特效
                })
            },
            /*封装定时器用于检查二维码状态*/
            checkQrcodeTimerFunc() {
                //1.清除定时器
                clearInterval(this.qrcodeObj.timer)
                if (this.qrcodeObj.code === "") {
                    return
                }
                //2.开启定时器,2s轮询查询二维码状态
                this.qrcodeObj.checkTimer = setInterval(() => {
                    checkQrCode(this.qrcodeObj.code).then(res => {
                        const {data, success} = res
                        const {code, msg} = data
                        this.qrcodeObj.style = success ? {"color": "blue"} : {"color": "red"}
                        this.qrcodeObj.message = msg
                        if (code === null && this.qrcodeObj.isScan) { //二维码过期,已扫描将不再自动获取
                            this.getQrCodeFunc()
                        } else if (code === "-1") { //授权失败,关闭定时器
                            clearInterval(this.qrcodeObj.checkTimer)
                        } else if (code === "0") {
                            this.qrcodeObj.style = {}
                        } else if (code === "1") {
                            this.qrcodeObj.isScan = false //已扫描,不会自动更新二维码
                            this.qrcodeObj.filter = true //开启滤镜,实现蒙版效果
                        } else if (code === "0") {
                            this.qrcodeObj.style = {}
                        } else if (code === "2") { //z,关闭定时器
                            clearInterval(this.qrcodeObj.checkTimer)
                            // 请求:登录
                            this.$store.dispatch('user/qrcodeLogin', this.qrcodeObj.code).then(() => {
                                this.$router.push({path: this.redirect || '/'})
                            }).catch(e => {
                                this.$message.error(e);
                            })
                        }
                    })
                }, 2000)
            }
        },
        mounted() {
            // 清除定时器
            clearInterval(this.timer)
            clearInterval(this.qrcodeObj.checkTimer)
        },
        beforeDestroy() {
            // 清除定时器
            clearInterval(this.timer);
            clearInterval(this.qrcodeObj.checkTimer);
        }
    }
</script>

<style scoped lang="less">
    * {
        font: 12px/3.0 "Microsoft YaHei", tahoma, arial, 'Hiragino Sans GB', '\5b8b\4f53', sans-serif;
    }

    .login {
        /*登录页面头部*/

        .login-header {
            padding: 22px 0;
            height: 70px;

            .logo {
                width: 1200px;
                margin: 0 auto;
                overflow: hidden;

                h1 {
                    display: block;
                    float: left;
                    zoom: 1;
                    width: 110px;
                    height: 44px;
                    vertical-align: middle;
                    font-size: 18px;

                    a {
                        text-decoration: none;
                        display: block;
                        color: #f40;
                        height: 45px;
                        width: 110px;
                        background-image: url("../../assets/login_logo.png");
                    }
                }

                .login-msg {
                    line-height: 16px;
                    padding: 6px 10px;
                    overflow: hidden;
                    background: #fef2f2;
                    border: 1px solid;
                }

                /*中部消息框*/

                .login-msg.error {
                    border-color: #ffb4a8;
                    background-color: #fef2f2;
                    color: #6C6C6C;
                }

                /*‘登录页面’改进建议按钮css*/

                .link {
                    float: right;
                    line-height: 44px;
                    color: #666;
                    font-size: 12px;
                    text-decoration: none;

                    /*图标*/

                    i {
                        font-size: 18px;
                        color: #f40;
                        font-style: normal;
                    }
                }

                .link:hover {
                    color: #f40;
                }
            }
        }

        /*登录页面内容*/

        .login-content {
            width: 100%;
            position: relative;

            /*大背景*/

            .login-newbg {
                position: absolute;
                z-index: 9;
                top: 0;
                left: 0;
                background-size: cover;
                background-repeat: no-repeat;
                background-position: center center;
                width: 100%;
            }

            /*大背景链接*/

            .login-adlink {
                width: 1200px;
                margin: 0 auto;
                position: relative;
                z-index: 1000;

                a {
                    position: absolute;
                    width: 630px;
                    height: 440px;
                    left: 80px;
                    top: 80px;
                    color: #f40;
                    text-decoration: none;
                }
            }

            /*登录表单*/

            .content-layout {
                width: 1200px;
                margin: 0 auto;
                overflow: hidden;
                position: relative;
                height: 600px;
                z-index: 999;

                .login-box-warp {
                    position: absolute;
                    top: 120px;
                    right: 60px;
                    width: 350px;
                    height: 453px;
                    background-color: rgba(255, 255, 255, 0.9);

                    .login-box {
                        width: 300px;
                        padding: 25px 25px 23px;
                        color: #6c6c6c;
                        position: relative;
                        margin: 0 auto;

                        /*登录表单输入框内容*/

                        .bd {
                            /*标准登录框 标题*/

                            .login-title {
                                height: 18px;
                                line-height: 18px;
                                font-size: 16px;
                                color: #3c3c3c;
                                margin-top: 9px;
                                padding-bottom: 8px;
                                font-weight: 700;
                            }

                            /*标准登录框*/

                            .static-form {
                                display: block;
                                position: relative;

                                /*form 表单*/

                                .J_Form {
                                    /*普通方式登录*/

                                    .field {
                                        margin-top: 20px;
                                        position: relative;

                                        /*发送验证码*/

                                        .send-code-btn {
                                            background: #fff;
                                            border: none;
                                            outline: none;
                                            color: #2e7ecd;
                                            font-size: 12px;
                                            position: absolute;
                                            top: 50%;
                                            right: -160px;
                                            transform: translateY(-50%);
                                        }
                                    }

                                    /*登录按钮*/

                                    .submit {
                                        margin-top: 20px;

                                        .J_Submit {
                                            line-height: 12px;
                                            width: 300px;
                                            height: 42px;
                                            border: 0;
                                            display: inline-block;
                                            overflow: hidden;
                                            vertical-align: middle;
                                            font-size: 16px;
                                            font-weight: 700;
                                            color: #fff;
                                            background: #f40;
                                            border-radius: 3px;
                                            cursor: pointer;
                                            zoom: 1;

                                        }

                                        .J_Submit:hover {
                                            background-color: #f52b00;
                                        }

                                    }

                                    /*其他登录方式*/

                                    .entries {
                                        .other-login {
                                            margin-top: 24px;
                                            line-height: 14px;

                                            a {
                                                width: 100px;
                                                display: inline-block;
                                                color: #6c6c6c;
                                                position: relative;
                                                text-align: center;
                                                text-decoration: none;

                                                /*图标*/

                                                i {
                                                    display: inline-block;
                                                    width: 20px;
                                                    height: 20px;
                                                    border-radius: 50%;
                                                    position: absolute;
                                                    left: 0;
                                                    top: 8px;
                                                }
                                            }

                                            /*人脸登录方式*/

                                            a.face-login {
                                                i {
                                                    font-size: 15px;
                                                    top: -5px;
                                                }
                                            }

                                            /*验证码登录方式*/

                                            a.weibo-login {
                                                i {
                                                    font-size: 15px;
                                                    top: -5px;
                                                }

                                                span {
                                                    margin-left: 10px;
                                                }
                                            }

                                            /*支付宝登录方式*/

                                            a.alipay-login {
                                                width: 110px;

                                                i {
                                                    background-image: url("../../assets/ali_icon.png");
                                                }
                                            }

                                            a:hover {
                                                color: rgb(255, 68, 0);
                                                text-decoration: underline;
                                            }
                                        }
                                    }

                                    /*尾部其他链接*/

                                    .login-links {
                                        margin-top: 25px;
                                        overflow: hidden;
                                        text-align: right;

                                        a {
                                            margin-right: 10px;
                                            color: #6c6c6c;
                                            text-decoration: none;
                                        }

                                        a:hover {
                                            text-decoration: underline;
                                        }
                                    }
                                }

                            }

                            /*人脸登录-提示信息*/

                            #faceLoginTipP {
                                text-align: center;
                                font-weight: bold;
                                margin-top: 30px;
                            }

                            /*二维码登录-提示信息*/

                            .qrcodeLoginTipP {
                                text-align: center;
                            }
                        }
                    }
                }
            }
        }
    }

</style>